package com.pzhu.user.rpc.server;

import com.google.protobuf.Empty;
import com.pzhu.base.common.utils.exceptions.Assert;
import com.pzhu.user.api.PermissionApi;
import com.pzhu.user.api.PermissionServiceGrpc;
import com.pzhu.user.domain.dto.converter.PermissionDtoConverter;
import com.pzhu.user.domain.ro.PermissionCreateRO;
import com.pzhu.user.domain.ro.PermissionSearchRO;
import com.pzhu.user.domain.ro.PermissionUpdateRO;
import com.pzhu.user.domain.vo.PermissionSearchVO;
import com.pzhu.user.service.impl.PermissionService;
import io.grpc.stub.StreamObserver;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import net.devh.boot.grpc.server.service.GrpcService;

@GrpcService
@RequiredArgsConstructor
public class PermissionServer extends PermissionServiceGrpc.PermissionServiceImplBase {

    private final PermissionService permissionService;

    private final PermissionDtoConverter permissionDtoConverter;

    @Override
    public void createPermission(PermissionApi.PermissionCreateRequest request, StreamObserver<PermissionApi.PermissionCreateResponse> responseObserver) {
        try {
            PermissionApi.PermissionCreateDTO permissionCreateDTO = request.getPermission();
            PermissionCreateRO permissionCreateRO = permissionDtoConverter.convert(permissionCreateDTO);
            Long permissionId = permissionService.create(permissionCreateRO);
            
            PermissionApi.PermissionCreateResponse.Builder builder = PermissionApi.PermissionCreateResponse.newBuilder();
            Optional.ofNullable(permissionId).ifPresent(builder::setPermissionId);
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            responseObserver.onError(e);
        }
    }

    @Override
    public void getPermissionById(PermissionApi.GetPermissionRequest request, StreamObserver<PermissionApi.PermissionResponse> responseObserver) {
        try {
            Long permissionId = request.getPermissionId();
            PermissionSearchVO permissionSearchVO = permissionService.info(permissionId);
            Assert.assertNotNull(permissionSearchVO, "权限不存在");
            
            PermissionApi.PermissionDTO permissionDTO = permissionDtoConverter.toDTO(permissionSearchVO);
            PermissionApi.PermissionResponse.Builder builder = PermissionApi.PermissionResponse.newBuilder();
            responseObserver.onNext(builder.setPermission(permissionDTO).build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            responseObserver.onError(e);
        }
    }

    @Override
    public void getPermissionByCode(PermissionApi.GetPermissionByCodeRequest request, StreamObserver<PermissionApi.PermissionResponse> responseObserver) {
        try {
            String permissionCode = request.getPermissionCode();
            PermissionSearchVO permissionSearchVO = permissionService.searchOne(PermissionSearchRO.builder().permissionCode(permissionCode).build());
            Assert.assertNotNull(permissionSearchVO, "权限不存在");
            
            PermissionApi.PermissionDTO permissionDTO = permissionDtoConverter.toDTO(permissionSearchVO);
            PermissionApi.PermissionResponse.Builder builder = PermissionApi.PermissionResponse.newBuilder();
            responseObserver.onNext(builder.setPermission(permissionDTO).build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            responseObserver.onError(e);
        }
    }

    @Override
    public void updatePermission(PermissionApi.UpdatePermissionRequest request, StreamObserver<PermissionApi.PermissionResponse> responseObserver) {
        try {
            Long permissionId = request.getPermissionId();
            PermissionApi.PermissionUpdateDTO permissionUpdateDTO = request.getPermission();
            PermissionUpdateRO permissionUpdateRO = permissionDtoConverter.convertUpdate(permissionUpdateDTO);
            
            boolean result = permissionService.update(permissionId, permissionUpdateRO);
            Assert.assertTrue(result, "更新权限失败");
            
            PermissionSearchVO permissionSearchVO = permissionService.info(permissionId);
            PermissionApi.PermissionDTO permissionDTO = permissionDtoConverter.toDTO(permissionSearchVO);
            PermissionApi.PermissionResponse.Builder builder = PermissionApi.PermissionResponse.newBuilder();
            responseObserver.onNext(builder.setPermission(permissionDTO).build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            responseObserver.onError(e);
        }
    }

    @Override
    public void deletePermission(PermissionApi.DeletePermissionRequest request, StreamObserver<Empty> responseObserver) {
        try {
            Long permissionId = request.getPermissionId();
            boolean result = permissionService.removeById(permissionId);
            Assert.assertTrue(result, "删除权限失败");
            
            responseObserver.onNext(Empty.newBuilder().build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            responseObserver.onError(e);
        }
    }

    @Override
    public void batchDeletePermissions(PermissionApi.BatchDeletePermissionsRequest request, StreamObserver<Empty> responseObserver) {
        try {
            List<Long> permissionIds = request.getPermissionIdsList();
            boolean result = permissionService.removeByIds(permissionIds);
            Assert.assertTrue(result, "批量删除权限失败");
            
            responseObserver.onNext(Empty.newBuilder().build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            responseObserver.onError(e);
        }
    }

    @Override
    public void getAllPermissions(PermissionApi.GetAllPermissionsRequest request, StreamObserver<PermissionApi.GetAllPermissionsResponse> responseObserver) {
        try {
            List<PermissionSearchVO> permissions = permissionService.getAllPermissions();
            List<PermissionApi.PermissionDTO> permissionDTOs = permissions.stream()
                    .map(permissionDtoConverter::toDTO)
                    .collect(Collectors.toList());
            
            PermissionApi.GetAllPermissionsResponse.Builder builder = PermissionApi.GetAllPermissionsResponse.newBuilder();
            builder.addAllPermissions(permissionDTOs);
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            responseObserver.onError(e);
        }
    }

    @Override
    public void assignPermissionsToRole(PermissionApi.AssignPermissionsToRoleRequest request, StreamObserver<Empty> responseObserver) {
        try {
            Long roleId = request.getRoleId();
            List<Long> permissionIds = request.getPermissionIdsList();
            boolean result = permissionService.assignPermissionsToRole(roleId, permissionIds);
            Assert.assertTrue(result, "分配权限给角色失败");
            
            responseObserver.onNext(Empty.newBuilder().build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            responseObserver.onError(e);
        }
    }

    @Override
    public void getRolePermissions(PermissionApi.GetRolePermissionsRequest request, StreamObserver<PermissionApi.GetRolePermissionsResponse> responseObserver) {
        try {
            Long roleId = request.getRoleId();
            List<PermissionSearchVO> rolePermissions = permissionService.getRolePermissions(roleId);
            List<PermissionApi.PermissionDTO> permissionDTOs = rolePermissions.stream()
                    .map(permissionDtoConverter::toDTO)
                    .collect(Collectors.toList());
            
            PermissionApi.GetRolePermissionsResponse.Builder builder = PermissionApi.GetRolePermissionsResponse.newBuilder();
            builder.addAllPermissions(permissionDTOs);
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            responseObserver.onError(e);
        }
    }

    @Override
    public void getUserPermissions(PermissionApi.GetUserPermissionsRequest request, StreamObserver<PermissionApi.GetUserPermissionsResponse> responseObserver) {
        try {
            Long userId = request.getUserId();
            List<PermissionSearchVO> userPermissions = permissionService.getUserPermissions(userId);
            List<PermissionApi.PermissionDTO> permissionDTOs = userPermissions.stream()
                    .map(permissionDtoConverter::toDTO)
                    .collect(Collectors.toList());
            
            PermissionApi.GetUserPermissionsResponse.Builder builder = PermissionApi.GetUserPermissionsResponse.newBuilder();
            builder.addAllPermissions(permissionDTOs);
            responseObserver.onNext(builder.build());
            responseObserver.onCompleted();
        } catch (Exception e) {
            responseObserver.onError(e);
        }
    }
}